#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int Maxn=1e6+7;
const int Mod=998244353;
int n,m;
int f1[Maxn],f2[Maxn],rt1,rt2;
int dep[Maxn],lca[Maxn],a[Maxn],sz[Maxn];
int dep1[Maxn],mp[Maxn],cnt;

ll ans;

vector<int>e1[Maxn],e2[Maxn];

void dfs1(int u,int ft){
    sz[u]=1;
    dep1[u]=dep1[ft]+1;
    for(auto v:e1[u]){
        if(v==ft) continue;
        dfs1(v,u);
        sz[u]+=sz[v];
    }
}
int lst;
void dfs2(int u,int ft){
    dep[u]=dep[f2[u]]+1;
    for(auto v:e2[u]){
        if(v==ft) continue;
        dfs2(v,u);
    }
}
bool vis[Maxn];
void dfslca(int now,int lc){
    lca[now]=lc;
    vis[now]=1;
    for(auto v:e2[now]){
        if(vis[v]) continue;
        int nc=lc;
        if(dep[v]<dep[lc]) nc=v;
        dfslca(v,nc);
    }
}
int poq=0;
void dfspth(int u,int now,int lc){
    mp[++cnt]=u;
    if(u<now){
        int x=u,y=now;ll val;
        if(lc!=u and now!=lc)
            val=1ll*sz[u]%Mod*sz[now]%Mod,cout<<"hh\n";
        
        else val=1ll*min(sz[u],sz[now])%Mod*(1+n-max(sz[mp[2]],sz[mp[cnt-1]]))%Mod;
        ans=(ans+val*dep[lca[now]]%Mod)%Mod;
        // cout<<"hel "<<u<<' '<<now<<" "<<val<<" "<<mp[2]<<" "<<mp[cnt-1] <<endl;
    }
    vis[now]=1;
    
    for(auto v:e1[now]){
        if(vis[v]) continue;
        int nc=lc;
        if(dep[v]<dep[lc]) nc=v;
        dfspth(u,v,nc);
    }
    --cnt;
}

int main(){
    freopen("tree.in","r",stdin);
    freopen("tree.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&f1[i]);
        if(!f1[i]) rt1=i;
        else e1[f1[i]].emplace_back(i),
             e1[i].emplace_back(f1[i]);
    }
    for(int i=1;i<=m;i++){
        scanf("%d",&f2[i]);
        if(!f2[i]) rt2=i;
        else e2[f2[i]].emplace_back(i),
             e2[i].emplace_back(f2[i]);
    }
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);

    dfs1(rt1,0);
    dfs2(rt2,0);
    for(int i=1;i<=n;i++){
        poq=0;
        for(int j=1;j<=m;j++) vis[j]=0;
        dfslca(a[i],a[i]);
        for(int j=1;j<=n;j++) vis[j]=0;
        dep1[0]=1e9;
        dfspth(i,i,i);
    }
    printf("%lld",ans);

    return 0;
}
/*
4 4
0 1 2 3
0 1 2 3
1 2 3 4

6 7
6 6 6 6 6 0
6 6 6 6 6 0 6
6 6 6 6 6 6
*/